package com.echo.util.impl;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.echo.fm.admin.auto.model.Admin;

public class HeaderParser {
	public static String getToken(HttpServletRequest request) {
		String token = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie c : cookies) {
				if (c.getName().equalsIgnoreCase("token")) {
					token = c.getValue();
				}
			}
		}
		return token;
	}
	
	public static Admin getUser(HttpServletRequest request){
		String token = getToken(request);
		HttpSession session = request.getSession(false);
		if(token!=null && session!=null){
			return(Admin) session.getAttribute(token);
		}
		return null;
	}

//	public static SystemUser getUser(HttpServletRequest request) {
//		String token = getToken(request);
//		HttpSession session = request.getSession(false);
//		if (token != null && session != null) {
//			return (SystemUser) session.getAttribute(token);
//		}
//		return null;
//	}

	public static String setToken(HttpServletRequest request, HttpServletResponse response, String token) {
		Cookie[] cookies = request.getCookies();
		boolean isExists = false;
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equalsIgnoreCase("token")) {
					isExists = true;
					cookie.setPath("/");
					cookie.setValue(token);
					response.addCookie(cookie);
				}
			}
			if (!isExists) {
				Cookie cookie = new Cookie("token", token);
				cookie.setPath("/");
				response.addCookie(cookie);
			}
		}
		return token;
	}

	public static String getIpAddr(HttpServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}
}
